// /common/UserSession.ts

// 定义持久化存储中使用的键
const IS_LOGGED_IN_KEY = 'isUserLoggedIn_persistent';
const LOGGED_IN_USERNAME_KEY = 'loggedInUsername_persistent';
const AUTH_TOKEN_KEY = 'authToken_persistent';

class UserSessionManager {
  /**
   * 初始化持久化存储链接
   * 应该在应用启动时调用一次
   */
  static initPersistentStorage(): void {
    // 将 AppStorage 的键链接到 PersistentStorage，使数据持久化
    PersistentStorage.persistProp(IS_LOGGED_IN_KEY, false);
    PersistentStorage.persistProp(LOGGED_IN_USERNAME_KEY, '');
    PersistentStorage.persistProp(AUTH_TOKEN_KEY, '');
    console.info('[UserSession] 持久化存储已初始化');
  }

  /**
   * 用户登录后，更新全局状态
   * @param username 登录的用户名
   * @param token 认证token
   */
  static login(username: string, token: string): void {
    AppStorage.setOrCreate(IS_LOGGED_IN_KEY, true);
    AppStorage.setOrCreate(LOGGED_IN_USERNAME_KEY, username);
    AppStorage.setOrCreate(AUTH_TOKEN_KEY, token);
    console.info(`[UserSession] 用户 ${username} 已登录，token: ${token?.substring(0, 10)}...`);
  }

  /**
   * 用户退出登录后，清除全局状态
   */
  static logout(): void {
    AppStorage.setOrCreate(IS_LOGGED_IN_KEY, false);
    AppStorage.setOrCreate(LOGGED_IN_USERNAME_KEY, '');
    AppStorage.setOrCreate(AUTH_TOKEN_KEY, '');
    console.info('[UserSession] 用户已退出登录，全局状态已清除。');
  }

  /**
   * 检查用户是否已登录
   */
  static isUserLoggedIn(): boolean {
    const isLoggedIn = AppStorage.get<boolean>(IS_LOGGED_IN_KEY) ?? false;
    console.info(`[UserSession] 检查登录状态: ${isLoggedIn}`);
    return isLoggedIn;
  }

  /**
   * 获取当前登录的用户名
   */
  static getLoggedInUsername(): string | undefined {
    const username = AppStorage.get<string>(LOGGED_IN_USERNAME_KEY);
    console.info(`[UserSession] 获取用户名: ${username || '未登录'}`);
    return username || undefined;
  }

  /**
   * 获取认证token
   */
  static getToken(): string | undefined {
    const token = AppStorage.get<string>(AUTH_TOKEN_KEY);
    console.info(`[UserSession] 获取token: ${token ? token.substring(0, 10) + '...' : '无token'}`);
    return token || undefined;
  }
}

export default UserSessionManager;